//
//  WBOAuthViewController.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/5.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit
import SVProgressHUD

let AppKey = "1212641753"

let AppSecret = "6c7b3c580e9744e5f64868ae46d9e1be"

let Redirect_Uri = "http://www.itcast.cn"

class WBOAuthViewController: UIViewController {
    
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {

        webView.delegate = self
        view = webView
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        requestOAuthLogin()
        setupNavUI()
        
    }

    private func requestOAuthLogin() {
        // 加载登录页面
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)"
        let urlRequest = URLRequest(url: URL(string: url)!)
        webView.loadRequest(urlRequest)
        
    }
    
    private func setupNavUI() {
        
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(target: self, action: #selector(cancel), title: "取消")
        navigationItem.rightBarButtonItem = UIBarButtonItem(target: self, action: #selector(autoFill), title: "自动填充")

    }
    
    @objc private func cancel() {
        
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFill() {
    webView.stringByEvaluatingJavaScript(from:"document.getElementById('userId').value='13456002051';document.getElementById('passwd').value='86873423';")
        
    }
    
}

// MARK: --WebView的代理方法
extension WBOAuthViewController:UIWebViewDelegate {
    
    // 将要开始加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(Redirect_Uri) == true {
            
            if let query = request.url?.query,query.hasPrefix("code=") {
                // 截取字符串从code=后面开始截取到最后
                let code = query.substring(from: "code=".endIndex)
                
                WBUserAccountViewModel.sharedViewModel.requestAccessToke(code: code, callBack: { (islogin:Bool) in
                    
                    if islogin {
                        
                        print("登录成功")
                        self.dismiss(animated: false, completion: { 
                            // 发生通知
                            NotificationCenter.default.post(name: NSNotification.Name( SwitchRootVCNotificationName), object: self)
                        })
                    } else {
                        
                        print("登录失败")
                    }
                    
                })
                
            } else{
                
                dismiss(animated: true, completion: nil)
            }
            
            // 不加载
            return false
            
        }
        
        return true
    }
    
    // 开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    // 结束加载
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    // 加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
    
}
